package com.bw.a2207a.view

import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bw.a2207a.R
import com.bw.a2207a.base.BaseActivity
import com.bw.a2207a.bean.GoodsBean
import com.bw.a2207a.databinding.ActivitySearchBinding
import com.bw.a2207a.db.CartDbUtil
import com.bw.a2207a.bean.SearchHistoryBean
import com.bw.a2207a.view.adapter.GoodsAdapter
import com.bw.a2207a.view.adapter.SearchHistoryAdapter
import com.bw.a2207a.viewmodel.HomeViewModel
import kotlin.String as String

@Route(path = "/main/SearchActivity")
class SearchActivity :
    BaseActivity<ActivitySearchBinding, HomeViewModel>(R.layout.activity_search) {
    //    var id = 1
    val querySearchs = mutableListOf<SearchHistoryBean>()
    lateinit var searchHistoryAdapter: SearchHistoryAdapter

    lateinit var etContent: String
    var page = 1
    val size = 10

    lateinit var adapter: GoodsAdapter
    val datas = mutableListOf<GoodsBean>()
    override fun initData() {
        viewModel.searchLiveData.observe(this) {
            querySearchs.clear()
            querySearchs.addAll(it)
            searchHistoryAdapter.notifyDataSetChanged()
        }

        viewModel.goodsLiveData.observe(this) {
            if (it.code == 200) {
                datas.addAll(it.data)
                adapter.notifyDataSetChanged()
            }
        }
    }

    override fun initView() {
//        etContent = binding.etSearch.text.toString()
        binding.mysearch.textView.setOnClickListener {
            //获取搜索输入的内容，保存至 搜索历史表中
            CartDbUtil.cartDb.getSearchDao()
                .insertSearch(SearchHistoryBean(null, binding.mysearch.etSearch.text.toString()))

            val newData = mutableListOf<GoodsBean>()
            //通过循环，添加符合搜索关键字的数据
            datas.forEach(){
                if(it.goods_desc.contains(binding.mysearch.etSearch.text.toString())){
                    newData.add(it)
                }
            }

            //通过过滤函数filter，过滤出符合条件的数据
           val dd = datas.filter { it.goods_desc.contains(binding.mysearch.etSearch.text.toString()) }

            binding.rvGoods.layoutManager = GridLayoutManager(this, 2)
            adapter = GoodsAdapter(R.layout.item_goods_layout, newData)
            binding.rvGoods.adapter = adapter

        }

        viewModel.searchHistory()

        viewModel.getGoods(0, page, size)

        binding.rvSearch.layoutManager = GridLayoutManager(this, 4)
        searchHistoryAdapter =
            SearchHistoryAdapter(this, R.layout.item_search_history_layout, querySearchs)
        binding.rvSearch.adapter = searchHistoryAdapter



        binding.rvGoods.layoutManager = GridLayoutManager(this, 2)
        adapter = GoodsAdapter(R.layout.item_goods_layout, datas)
        binding.rvGoods.adapter = adapter

    }

}